package GameServer

import (
	"PBMessage"
	. "SGNet"
	"container/list"
	proto "github.com/golang/protobuf/proto"
)

type GameMatch struct {
	hall        *GameHall
	queueData   *list.List
	cachePlayer []*ClientPlayer
}

func NewMatchGame(hall *GameHall) *GameMatch {
	queue := &GameMatch{}
	queue.queueData = list.New()
	queue.hall = hall
	return queue
}

func (this *GameMatch) Add(player *ClientPlayer) {
	player.queueRef = this.queueData.PushBack(player)

}
func (this *GameMatch) Remove(player *ClientPlayer) {
	this.queueData.Remove(player.queueRef)
}

func (this *GameMatch) loop() {
	for this.queueData.Len() >= this.hall.RoomSize {
		for i := 0; i < this.hall.RoomSize; i++ {
			if i == 0 {
				this.cachePlayer = make([]*ClientPlayer, this.hall.RoomSize)
			}
			lstClient := this.queueData.Front()
			this.cachePlayer[i] = lstClient.Value.(*ClientPlayer)
			this.cachePlayer[i].queueRef = nil
			this.queueData.Remove(lstClient)
			if i == this.hall.RoomSize-1 {
				this.MacthToReadRoom(this.cachePlayer)
			}
		}
	}
}

//匹配成功进入准备房间.
func (this *GameMatch) MacthToReadRoom(player []*ClientPlayer) {
	room := NewReadyRoom(player)
	room.ToClient()
	GetGameHall().AddReadyRoom(room)
}

func (this *GameMatch) CS_MatchGame_Handler(msg *Message) {
	packetData := &PBMessage.CS_MatchGame{}
	proto.Unmarshal(msg.Data, packetData)
	player := this.hall.GetPlayer(packetData.GetUserName())
	if player == nil {
		return
	}
	this.Add(player)
	player.PlayerState = PLAYERSTATE_MATCHGAME
	retMatchGame := &PBMessage.SC_RetMatchGame{RetType: proto.Int32(0)}
	msg.Sess.SendPacket(PBMessage.PBID_SC_RetMatchGame, retMatchGame)
}

func (this *GameMatch) CS_CancelMatchGame_Halder(msg *Message) {
	packetData := &PBMessage.CS_MatchGame{}
	proto.Unmarshal(msg.Data, packetData)
	player := this.hall.GetPlayer(packetData.GetUserName())
	if player == nil {
		return
	}
	this.Remove(player)
	RetDara := &PBMessage.SC_RetCancelMatch{RetType: proto.Int32(0)}
	msg.Sess.SendPacket(PBMessage.PBID_SC_RetCancelMatch, RetDara)
}
